package com.fjec.market.rabbitmq.provider;

import com.fjec.common.protocol.FjecFruitsProto;
import com.google.common.base.Joiner;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class OrderTimeoutProvider {

    @Value("${fjec.market.order.timeout.exchange.name}")
    private String exchangeName;

    @Value("${fjec.market.order.timeout.router.key}")
    private String routingKey;

    /**
     * 过期时间，单位分钟
     */
    @Value("${fjec.market.order.timeout.value}")
    private Integer timeout;

    @Resource(name = "phyOrderAmqpTemplate")
    private RabbitTemplate phyOrderAmqpTemplate;

    public void sendDelayMsgForOrderTimeout(List<Long> orderIdList) {
        FjecFruitsProto.OrderTimeout.Builder builder = FjecFruitsProto.OrderTimeout.newBuilder();
        for (Long orderId : orderIdList) {
            builder.addOrderId(orderId);
        }
        FjecFruitsProto.FjecFruitsMsg msg = FjecFruitsProto.FjecFruitsMsg.newBuilder()
                .setOrderTimeout(builder.build())
                .build();
        // 加入延时头
        MessageProperties props = new MessageProperties();
        props.setHeader("delay", timeout * 60 * 1000);
        Message message = new Message(msg.toByteArray(), props);
        CorrelationData correlationData = new CorrelationData(Joiner.on("|").join(orderIdList));
        phyOrderAmqpTemplate.convertAndSend(exchangeName, routingKey, message, correlationData);
    }

}
